import qs from "querystring";
export default function parseBody(req) {
  return new Promise((resolve, reject) => {
    // 将异步api包裹成promise 给外界用
    const arr = [];
    req.on("data", function (chunk) {
      arr.push(chunk);
    });
    req.on("end", function () {
      // 没有考虑文件的情况  表单 json格式
      let data = Buffer.concat(arr).toString();
      let contenntType = req.headers["content-type"];
      if (contenntType === "application/json") {
        data = JSON.parse(data);
      }
      if (contenntType === "application/x-www-form-urlencoded") {
        data = qs.parse(data); // 会自动用 & 和 = 来分割
      }
      resolve(data);
    });
  });
}
